#!/sbin/openrc-run
# Copyright 2006-2012 Gentoo Foundation
# Distributed under the terms of the GNU General Public License, v2 or later

extra_commands="import"

depend() {
	need net
}

# Substitute common default values
MTN_USER=${MTN_USER:-monotone}
MTN_GROUP=${MTN_GROUP:-monotone}
MTN_KEY=${MTN_KEY:-monotone@`hostname --fqdn`}
MTN_CONFDIR=${MTN_CONFDIR:-/etc/monotone}
MTN_COMMON="--norc --confdir=${MTN_CONFDIR} \
	--keydir=${MTN_KEYDIR:-/var/lib/monotone/keys} \
	--db=${MTN_DB:-/var/lib/monotone/default.mtn} \
	--rcfile=${MTN_CONFDIR}/hooks.lua --log=/var/log/monotone/monotone.log"
	#--dump=$ERRORLOG
MTN_PIDFILE="/var/run/monotone/monotone.pid"
MTN_HOME=$(awk -F: -vuid=$MTN_USER -vuser=$MTN_USER '$3 == uid || $1 == user { print $6 }' < /etc/passwd)

dbexists() {
	# Create the database if it doesn't exist
	if [ ! -e ${MTN_DB:-/var/lib/monotone/default.mtn} ]; then
		ebegin "Creating monotone database"
		start-stop-daemon --start \
			--user ${MTN_USER} --group ${MTN_GROUP}  \
			--exec /usr/bin/mtn -- ${MTN_COMMON} db init
		eend $?
	fi
	if [ ! -e ${MTN_KEYDIR:-/var/lib/monotone/keys}/${MTN_KEY} ]; then
		ebegin "Creating monotone server keypair"
		export MTN_PWD=${RANDOM}
		yes "${MTN_PWD}" | \
			start-stop-daemon --start \
			--user ${MTN_USER} --group ${MTN_GROUP}  \
			--exec /usr/bin/mtn -- ${MTN_COMMON} genkey ${MTN_KEY}

		eend $?
		# Update the password lua hook
		cat > ${MTN_CONFDIR}/passphrase.lua <<EOF
-- This file is automaticaly generated by the init scripts.
-- If you want to add custom hooks, edit ${MTN_CONFDIR}/hooks.lua
-- If you want to change the settings, please edit /etc/conf.d/monotone

function get_passphrase(identity)
  if (identity == "${MTN_KEY}") then
    return "${MTN_PWD}"
  end
  return false
end
EOF
	fi
}

start() {
	cd ${MTN_HOME}
	dbexists

	ebegin "Starting monotone server"
	start-stop-daemon --start --background \
		--user ${MTN_USER} --group ${MTN_GROUP}  \
		--exec /usr/bin/mtn -- ${MTN_COMMON} --pid-file=${MTN_PIDFILE} \
		--key=${MTN_KEY} --bind=${MTN_ADDRESS:-0.0.0.0} serve
	eend $?
}

stop() {
	ebegin "Stopping monotone server"
	start-stop-daemon --stop --quiet --pidfile ${MTN_PIDFILE}
	eend $?
}

import() {
	cd ${MTN_HOME}
	dbexists

	# Read packets into the database
	einfo "Importing packets to monotone database"
	cat | /usr/bin/mtn ${MTN_COMMON} read
	eend $?
}
